package com.chen.baopintao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.swift.util.http.WebClient;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import goods.baopintao.util.HttpUtil;

public class Test {

	public static void main(String[] args) throws Exception {
		Test service = new Test();
		String appToken = "89297CCE255D7ED";
		String appKey = "848ac6db03e4a4de49e1a3040ed2607f";
		String getGoodsListUrl = "http://m.baopintao.com/index.php?s=/api/replace/getItems.html";
		List<Item> list = service.getGoodsList(service.getGoodsPageCount(appToken,appKey,getGoodsListUrl), 1,appToken,appKey,getGoodsListUrl);
		int n = 0;
		List<Item> result = new ArrayList<Item>();
		for(Item item : list){ 
			if("1".equals(item.getTax())){//1完税 0未税
				String goods_stock = item.getGoods_stock();
				System.out.println(item.getName() + "," + goods_stock);
				if(Integer.parseInt(goods_stock) < 10){
					result.add(item);
				}
			}
		}
		//System.out.println(result.size());
		Test.deal(result);
	    //String listStr = new Gson().toJson(result);  
		//Test.saveFile(listStr);
		//Test.dealWithGoods("375","FF10001",result);
//		List<String> data = DBTools.testGetSKu();
//		for(String s:data){
//			System.out.println(s);
//		}
//		Test.dealWithImg(data);
		//Test.getHTMLInLine("4712688932585");
	}
	
	
	public static void deal(List<Item> list){
		StringBuilder result = new StringBuilder();
		for(Item item : list){
			result.append("insert into `豹品淘商品` values(");
			result.append("'" + item.getName() + "',");
			result.append("'" + item.getIntro() + "',");
			result.append("'" + item.getPrice() + "',");
			//taxTotal
			result.append("'" + item.getTaxTotal() + "',");
			result.append("'" + item.getSettlement_price() + "',");
			result.append("'" + item.getGoods_stock() + "',");
			result.append("'" + item.getWarehouse() + "',");
			result.append("'" + item.getTax() + "',");
			result.append("'" + item.getWeight() + "',");
			result.append("'" + item.getCate() + "',");
			result.append("'" + item.getBrand() + "',");
			result.append("'" + item.getGoodsModel() + "',");
			result.append("'" + item.getOrigin_name() + "',");
			result.append("'" + item.getProduct_sku() + "',");
			result.append("'" + item.getImg() + "',");
			result.append("'" + item.getImg_b() + "',");
			result.append("'" + item.getInfo() + "');");
			result.append("\n");
		}
		System.out.println(result.toString());
	}
	
	public Integer getGoodsPageCount(String appToken,String appKey,String getGoodsListUrl){
		try {
			Map<String, String> param = new HashMap<String, String>();
			param.put("appToken", appToken);
			param.put("appKey", appKey);
			StringBuilder builder = new StringBuilder();
			List<NameValuePair> paramList = new ArrayList<NameValuePair>();
			for (String key : param.keySet()) {
				builder.append(key + "=" + param.get(key) + "&");
				paramList.add(new BasicNameValuePair(key, param.get(key)));
			}
			String s = HttpUtil.doJSONPost(paramList,getGoodsListUrl);
			JsonObject obj = new JsonParser().parse(s).getAsJsonObject();
			JsonObject dataObj = obj.get("data").getAsJsonObject();
			return dataObj.getAsJsonPrimitive("pageCount").getAsInt();
		} catch (Exception e) {
			e.getMessage();
		}
		return 0;
	}
	
	public List<Item> getGoodsList(Integer pageSize,Integer pageNo,String appToken,String appKey,String getGoodsListUrl){
		try {
			Map<String, String> param = new HashMap<String, String>();
			param.put("appToken", appToken);
			param.put("appKey", appKey);
			if(pageSize == null || pageSize <= 0){
				pageSize = 10;
			}
			if(pageNo == null || pageNo <= 0){
				pageNo = 1;
			}
			param.put("ps", pageSize + "");
			param.put("pn", pageNo + "");
			
			StringBuilder builder = new StringBuilder();
			List<NameValuePair> paramList = new ArrayList<NameValuePair>();
			for (String key : param.keySet()) {
				builder.append(key + "=" + param.get(key) + "&");
				paramList.add(new BasicNameValuePair(key, param.get(key)));
			}
			String s = HttpUtil.doJSONPost(paramList,getGoodsListUrl);
			JsonObject obj = new JsonParser().parse(s).getAsJsonObject();
			JsonObject dataObj = obj.get("data").getAsJsonObject();
			JsonArray itemListArr = dataObj.get("itemList").getAsJsonArray();
			List<Item> itemList = new Gson().fromJson(itemListArr, new TypeToken<List<Item>>(){}.getType()); 
			return itemList;
		} catch (Exception e) {
			e.getMessage();
		}
		return null;
	}

	public static File saveFile(String data){
		try {
			File file = new File("E:\\豹品淘完税商品.txt");

			if (!file.exists()) {
				file.createNewFile();
			}
			
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(data);
			bw.close();
			return file;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            StringBuilder sb = new StringBuilder();
            int line = 1;
            // 涓�娆¤鍏ヤ竴琛岋紝鐩村埌璇诲叆null涓烘枃浠剁粨鏉�
            while ((tempString = reader.readLine()) != null) {
                // 鏄剧ず琛屽彿
            	sb.append(tempString);
                line++;
            }
            reader.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return "";
    }
	
	public static String getHTMLInLine(String sku) {
		String url = "http://imagejifenfu.oss-cn-hangzhou.aliyuncs.com/goodsBusiness/APPGoodsHelp/"+sku+ ".html";
		String data = WebClient.retrieveWebContent(url);
		System.out.println(data);
		return data;
	}
	
	public static void dealWithImg(List<String> list){
		//http://imagejifenfu.oss-cn-hangzhou.aliyuncs.com/goodsBusiness/APPGoodsHelp/4712688932585.html
		for(String sku:list){
			System.out.println("sku="+sku);
			//if("4711561462942".equals(sku)){
				String htmlStr = getHTMLInLine(sku);
				htmlStr = htmlStr.replaceAll("<br/>", "");
				int begin = htmlStr.indexOf("</title>")+"</title>".length();
				String left = htmlStr.substring(0, begin);
				System.out.println("left="+left);
				System.out.println("htmlStr="+htmlStr);
				int end = htmlStr.indexOf("</head>");
				htmlStr = left + "<style> img { vertical-align: top;} </style>" + htmlStr.substring( end);
				
				System.out.println("a="+htmlStr);
				File file = saveFile(htmlStr);
				try {
					String imgUrl = AliyunFileService2.uploadFile(file, "goodsBusiness/APPGoodsHelp/"+sku+".html");
				} catch (Exception e) {
					e.printStackTrace();
				}
			//}
			
		}
	}
	
	public static String genImgHtml(String title,List<String> imgs){
		String htmlStr = "<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"><title>"+title+"</title><style>img {vertical-align: top;}</style></head><body style=\"margin: 0px;\">";
		for(String img:imgs){
			htmlStr += "<img style=\"-webkit-user-select: none;width:100%\" alt=\"\" src=\""+img+"\">";
		}
		htmlStr += "</body></html>";
		return htmlStr;
	}
	
//	public static void dealWithGoods(String goodsTypeId,String goodsCode,List<Item> list){
//		for(int i=0;i<list.size();i++){
//			Item item = list.get(i);
//			String s = "insert into goods(id,goodsTypeId,state,goodsCode,goodsFullName,goodsName,isAllUse,supplyType,price,goodsSize) values(";
//			String goodsFullName = item.getName();
//			String goodsName = item.getName();
//			String price = new BigDecimal(item.getPrice()).multiply(new BigDecimal(100)).intValue() + "";
//			String goodsSize = item.getGoodsModel();
//			
//			String newGoodsCode = goodsCode + (i+1);
//			s += "null,"+goodsTypeId+",0,";
//			s += "'" + newGoodsCode + "',";
//			s += "'" + goodsFullName + "',";
//			s += "'" + goodsName + "',";
//			s += "0,";
//			s += "1,";
//			s += price + ",";
//			s += "'" + goodsSize + "');";
//			System.out.println(s);
//		}
//	}
}
